package com.wgly.question.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.wgly.question.bean.Options;
import com.wgly.question.bean.Topic;
@Service
public class WritesSqlService{
	public class WritesSql implements Callable<String> {
		private String file;
	    public WritesSql(String file) {
			// TODO Auto-generated constructor stub
	    	this.file=file;
		}	
		@Override
		public String call() throws Exception {
			// TODO Auto-generated method stub
			return file;
		}
	}
	public void  WritesSqlService(String file) throws Exception {
		ExecutorService pool = Executors.newFixedThreadPool(10);
		WritesSql writesSql = new WritesSql(file);
		Future<String> future = pool.submit(writesSql);
		excel(future.get());
	}
	public static void excel(String file) throws Exception {
		FileInputStream fis = new FileInputStream(new File(file));
		XSSFWorkbook workbook = new XSSFWorkbook(fis);
		XSSFSheet sheet = workbook.getSheetAt(0);
		int firstRowNum = sheet.getFirstRowNum();
		int lastRowNum = sheet.getLastRowNum();
		for(int i=firstRowNum;i<lastRowNum+1;i++) {
			XSSFRow row = sheet.getRow(i);
			if(row!=null) {
				int firstCellNum = row.getFirstCellNum();
				int lastCellNum = row.getLastCellNum();
				List<String> list = new ArrayList<String>();
				for(int j=firstCellNum;j<lastCellNum;j++) {
					list.add(row.getCell(j).toString());
				}
			    Topic topic = new Topic();
				topic.setTitle(list.get(0));
				String type = list.get(1);
				//将type转换为整数
				try {
					int indexOf = type.indexOf('.');
					type=type.substring(0, indexOf);
				}
				catch (StringIndexOutOfBoundsException e) {
					type= list.get(1);
				}
				topic.setType(type);
				topic.setProblem(list.get(2));
				if(TopicService.checkProblem(topic.getProblem())) {
				TopicService.writesTopic(topic);
				if(list.get(3).length()!=0) {
				String[] line= list.get(3).toString().split("====");
				int tid=TopicService.retrieve(list.get(2));
				for(int j=0;j<line.length;j++) {
					String []arr=line[j].split(",");
						Options options = new Options();
						options.setTid(tid);
						options.setLableIndex(arr[0]);
						options.setLabel(arr[1]);
						options.setIsAnswer(arr[2]);
						OptionsService.writesOptions(options);
				}
				}
				}
			}
		}
	}
}